/**
 * 管理与微信交互的所有凭据,包括access_token, jsapi_ticket等
 * Created by dongchen on 16/5/11.
 */
var fs = require('fs');
var config = require('config');
var coRequest = require('co-request');
var dao = require('../dao');

var
    appId = config.appId,
    secret = config.secret;

function * isNeedRefresh(type){
    var license = yield dao.License.findOne();
    if(license && license[type]){
        var tokenObj = license[type];
        var curTime = new Date().getTime();
        var expiresTime = tokenObj.startTime + tokenObj.expires_in * 1000;
        return (expiresTime - curTime) < (300 * 1000);
    }else{
        return true;
    }
}

function * saveAccessToken(resp) {
    resp.startTime = new Date().getTime();
    var data = {
        access_token : resp
    };

    var license = yield dao.License.findOne();
    if(license){
        yield license.update(data);
    }else{
        yield new dao.License(data).save();
    }
}

function * saveLicense(type, resp){
    resp.startTime = new Date().getTime();
    var data = {};
    data[type] = resp;

    var license = yield dao.License.findOne();
    if(license){
        yield license.update(data);
    }else{
        yield new dao.License(data).save();
    }
}

function * readAccessToken() {
    var license = yield dao.License.findOne();
    return license.access_token.access_token;
}

function * readLicense(type){
    var license = yield dao.License.findOne();
    return license[type].ticket;
}

function getAccessToken(isNew) {
    return function *() {
        if (isNew || (yield isNeedRefresh('access_token'))) {
            var accessUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${secret}`;

            var response = yield coRequest.get(accessUrl);
            var respJson = JSON.parse(response.body);

            if (respJson.errcode) {
                throw response.body;
            } else {
                console.log(response.body);
                yield saveAccessToken(respJson);
                return respJson.access_token;
            }
        } else {
            return yield readAccessToken();
        }
    }
}

function getJsApiTicket(isNew){
    var type = 'jsapi_ticket';
    return function * (){
        if(isNew || (yield isNeedRefresh(type))){
            var token = yield getAccessToken();
            var ticketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`;

            var response = yield coRequest.get(ticketUrl);
            var respJson = JSON.parse(response.body);

            if (respJson.errcode !== 0) {
                throw response.body;
            } else {
                console.log(response.body);
                yield saveLicense(type, respJson);
                return respJson.ticket;
            }
        }else{
            return yield readLicense(type);
        }
    }
}


module.exports = {
    access_token : getAccessToken,
    jsapi_ticket : getJsApiTicket
};